package com.ieds.modules.common.elasticsearch;

import com.ieds.modules.common.Util.StringUtil;
import org.apache.log4j.Logger;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 全文检索word转换文本
 * @author hugejile
 * @version 20200903
 */
public class WordXFileTextExtrator {

	/**
	 * 创建log对象
	 */
//	private static final Logger log = Logger.getLogger(WordXFileTextExtrator.class);

	private final static String doc = ".doc";
	private final static String docx = ".docx";

	public static String getText(File file) throws IOException {
		// 如果文件为空的话直接返回空值
		if (file.length() == 0) {
	        return "";
		}

		StringBuffer stringBuffer = null;
		FileInputStream in = null;
		try {
			stringBuffer = new StringBuffer();
			in = new FileInputStream(file);

			// 扩展名为doc
			if (file.getPath().endsWith(doc)) {
				WordExtractor wordExtractor = new WordExtractor(in);
				stringBuffer.append(wordExtractor.getText());

//				HWPFDocument wordExtractor = new HWPFDocument(in);
//				System.out.println(wordExtractor.getDocumentText());
//				stringBuffer.append(wordExtractor.getDocumentText());
			// 扩展名为docx
			} else if (file.getPath().endsWith(docx)) {
				XWPFDocument xwpfDocument = new XWPFDocument(in);
				XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(xwpfDocument);
				stringBuffer.append(xwpfWordExtractor.getText());
			} else {
				return "";
			}
		} catch (IOException e) {
//			log.error("getText() 失败！", e);
		} finally {
			if(in != null) {
				in.close();
			}
		}
		return StringUtil.washString(stringBuffer.toString());
	}

	public static void main(String[] args) {
		File file = new File("E:\\ceshi\\ceshi.docx");
		try {
			System.out.println(WordXFileTextExtrator.getText(file));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
